package com.yuke.cloud.service.uac.controller.frontend;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.base.constant.GlobalConstant;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.uac.dto.SupplierApiDto;
import com.yuke.cloud.service.api.wmc.dto.WarehouseInfoDto;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.uac.dto.UserRegisterDto;
import com.yuke.cloud.service.uac.entity.AccSupplier;
import com.yuke.cloud.service.uac.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
* Created by zn on 2020/10/06.
*/
@Api(value = "WEB - AccSupplierController", tags = "处理AccSupplier相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/acc/supplier")
public class AccSupplierController extends BaseController {
    @Resource
    private AccSupplierService accSupplierService;
    @Resource
    private AccUserRoleService accUserRoleService;
    @Resource
    private AccUserService accUserService;
    @Resource
    private AccGroupService accGroupService;
    @Resource
    private AccDeliveryAddressService accDeliveryAddressService;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;
    @Resource
    private SmcFeignApi smcFeignApi;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "accSupplier", value = "该数据记录的POJO") @RequestBody AccSupplier accSupplier) {
        accSupplierService.save(accSupplier);
        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        accSupplierService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "accSupplier", value = "需要修改的内容") @RequestBody AccSupplier accSupplier) {
        accSupplierService.update(accSupplier);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<AccSupplier> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        AccSupplier accSupplier = accSupplierService.findById(id);
        return WrapMapper.ok(accSupplier);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<AccSupplier>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<AccSupplier> list = accSupplierService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @PostMapping("/test")
    @Transactional
    @ApiOperation(httpMethod = "POST", value = "新增一条记录和user记录")
    public Wrapper addSupplierAndUser(@ApiParam(name = "accSupplier", value = "该数据记录的POJO") @RequestBody AccSupplier accSupplier) {
        if (accSupplier == null || accSupplier.getSupplierName() == null || accSupplier.getMobile() == null){
            return WrapMapper.error("参数错误！供应商名称或电话为空");
        }
        if (accSupplier.getRegionProvinceId() == 0 || accSupplier.getRegionCityId() == 0 || accSupplier.getRegionCountyId() == 0){
            return WrapMapper.error("参数错误！请完善地址信息！");
        }
        Example example = new Example(AccSupplier.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andCondition("supplier_name = '"+ accSupplier.getSupplierName() + "' or mobile ='"+ accSupplier.getMobile()+"'");
        Integer i = accSupplierService.selectCountByExample(example);
        if (i > 0){
            return WrapMapper.error("存在相同的供应商名称或电话号码！请检查后提交！");
        }

        //填充用户信息
        UserRegisterDto userRegisterDto = new UserRegisterDto();
        userRegisterDto.setMobileNo(accSupplier.getMobile());
        userRegisterDto.setLoginPwd("123456");
        userRegisterDto.setConfirmPwd("123456");
        userRegisterDto.setRegisterSource("0");
        userRegisterDto.setAddress(accSupplier.getAddress());
        userRegisterDto.setLoginName( accSupplier.getSupplierName());
        Long userId = accUserService.autoRegisterUser(userRegisterDto);

        if (userId > 0){
           accSupplier.setUserId(userId);
        }else{
            return WrapMapper.error("保存用户信息错误！");
        }


        //可以考虑添加店铺ID
        accSupplierService.save(accSupplier);

        if (accSupplier.getFactoryId() == null || accSupplier.getFactoryId() < 1){
            //如果有factoryId，就给创建店铺，绑定仓库，创建能在平台运营的身份。
            // 否则就直接返回，只创建普通用户信息，成为普通供货商。
            return WrapMapper.ok("保存经销商信息成功！");
        }

        //添加供应商角色权限
        accUserRoleService.saveRoleUser(accSupplier.getUserId(), GlobalConstant.Sys.SUPPLIER_ROLE_ID);

        Long warehouseId = accSupplier.getWarehouseId();

        //保存商店
        Integer num = 0;
        ShopInfoDto shopInfoDto = new ShopInfoDto();
        shopInfoDto.setShopId(generateId());
        shopInfoDto.setShopName(accSupplier.getSupplierName());
        shopInfoDto.setUserId(accSupplier.getUserId());
        shopInfoDto.setMobile(accSupplier.getMobile());
        shopInfoDto.setRegionCityId(accSupplier.getRegionCityId());
        shopInfoDto.setRegionProvinceId(accSupplier.getRegionProvinceId());
        shopInfoDto.setRegionCountryId(accSupplier.getRegionCountryId());
        shopInfoDto.setRegionCountyId(accSupplier.getRegionCountyId());
        shopInfoDto.setAddress(userRegisterDto.getAddress());
        shopInfoDto.setWarehouseId(warehouseId);
        shopInfoDto.setShopType((byte)3);

        Wrapper<List<WarehouseInfoDto>>  wareInfo = wmcStorageFeignApi.getWarehouseInfo(Arrays.asList(warehouseId));
        WarehouseInfoDto warehouseInfoDto = new WarehouseInfoDto();
        if (wareInfo.getCode() == 200) {
            warehouseInfoDto = wareInfo.getResult().get(0);
            shopInfoDto.setLongitude(warehouseInfoDto.getLongitude());
            shopInfoDto.setLatitude(warehouseInfoDto.getLatitude());
         }


        //保存店铺信息
        num = smcFeignApi.saveShop(shopInfoDto);
        //保存收货地址
        accDeliveryAddressService.saveUserDeliveryAddress(shopInfoDto);

        if (!num.equals(1)) {
            //商店保存失败
            return WrapMapper.error("保存店铺信息错误！");
        } else {
            accUserRoleService.saveRoleUser(accSupplier.getUserId(), GlobalConstant.Sys.SELLER_ROLE_ID);
        }

        //仓库绑店铺
        Long shopId = shopInfoDto.getShopId();
        wmcStorageFeignApi.saveWarehouseShop(warehouseId,shopId);

        return WrapMapper.ok();
    }


    @GetMapping("/getSupplierList")
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<List<AccSupplier>> getSupplierList() {
        List<AccSupplier> list = accSupplierService.getSupplierList();
        return WrapMapper.ok(list);
    }

    /**
     * 由厂家信息添加到供应商中，包括创建用户的账号，店铺信息，经销商信息，仓库信息
     */
    @PostMapping("/factoryTosupplier")
    @ApiOperation(httpMethod = "POST", value = "新增一条记录和user记录")
    public Wrapper factoryTosupplier(@ApiParam(name = "accSupplier", value = "该数据记录的POJO") @RequestBody AccSupplier accSupplier) {

        this.addSupplierAndUser(accSupplier);

        return WrapMapper.ok();
    }

    //根据名称筛选 或者Id筛选
    @PostMapping("/findSupplierByName")
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<SupplierApiDto>> findSupplierByName(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                               @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                               @ApiParam(name = "accSupplier", value = "该数据记录的POJO") @RequestBody SupplierApiDto supplierApiDto) {
        PageHelper.startPage(page, size);
        List<SupplierApiDto> list = accSupplierService.findSupplierByName(supplierApiDto);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }
}













































































































































































































































































































































































































































































































































































































































































































































































